import React, { use, useState, useEffect } from 'react';
import style from './index.module.css';
import { Button, Input, Table, Space, Modal, Card, Row, Col, Form, message, Radio } from 'antd';
import { addEmployee, getEmployeeListWithPage } from '@/redux/home/rightPages/EmployeeManagement/EmployeeManagement';



export default function EmployeeManagement() {
  const [visible, setVisible] = useState(false);
  const [form] = Form.useForm();
  const [employeeList, setEmployeeList] = useState([]);
  const [pageObject, setPageObject] = useState({
    currentPage: 1,
    pageNum: 5,
    total: 0,
    hasNext: false,
    hasLast: false,
  });
  const [condition, setCondition] = useState({});
  const columns = [
    {
      title: '员工姓名',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '账号',
      dataIndex: 'account',
      key: 'account',
    },
    {
      title: '手机号',
      dataIndex: 'phoneNumber',
      key: 'phoneNumber',
    },
    {
      title: '账号状态',
      dataIndex: 'status',
      key: 'status',
    },
    {
      title: '最后操作时间',
      dataIndex: 'updateDateTime',
      key: 'updateDateTime',
    },
    {
      title: '操作',
      key: 'action',
      render: (text, record) => (
        <Space size="middle">
          <a onClick={handleModify(record)}>修改</a>
          <a>禁用</a>
        </Space>
      ),
    },
  ];

  useEffect(() => {
    fetchEmployeeList();
  }, [pageObject.currentPage, pageObject.pageNum]);

  const fetchEmployeeList = () => {
    const params = {
      pageSize: {
        currentPage: pageObject.currentPage,
        pageNum: pageObject.pageNum,
      },
    }
    getEmployeeListWithPage(params).then((res) => {
      const { data } = res;
      setEmployeeList(data.resultData.employees);
      setPageObject(data.resultData.pageObject);
    });
  };

  const handleTableChange = (pagination) => {
    setPageObject({
      currentPage: pagination.current,
      pageNum: pagination.pageSize,
    });
  };
  const clickHandler = () => {
    setVisible(true);
  };

  const queryClickHandler = () => {
    const params = {
      pageSize: {
        currentPage: pageObject.currentPage,
        pageNum: pageObject.pageNum,
      },
      condition: {
        name: condition.name,
      },
    }
    getEmployeeListWithPage(params).then((res) => {
      const { data } = res;
      setEmployeeList(data.resultData.employees);
      setPageObject(data.resultData.pageObject);
    });
  };
  const saveOnClick = () => {
    form.validateFields().then((values) => {
      addEmployee(values).then((res) => {
        const { data } = res;
        if (data.resultCode === 200) {
          message.success('保存成功');
          setVisible(false);
        } else {
          message.error(data.resultMessage);
        }
      });
    }).catch((error) => {
      message.error("系统异常，请重试");
    }).finally(() => {
      fetchEmployeeList();
    });
  };

  const saveAndKeepAddingOnClick = () => {
    form.validateFields().then((values) => {
      addEmployee(values).then((res) => {
        const { data } = res;
        if (data.resultCode === 200) {
          message.success('保存成功');
          form.resetFields();
        } else {
          message.error(data.resultMessage);
        }
      });

    }).catch((error) => {
      message.error('保存失败');
    }).finally(
      () => fetchEmployeeList()
    );
  };

  const cancelOnClick = () => {
    setVisible(false);
    form.resetFields();
    fetchEmployeeList();
  };

  const handleModify = (record) => () => {
    form.setFieldsValue({
      account: record.account,
      name: record.name,
      phoneNumber: record.phoneNumber,
    });
    setVisible(true);
  };

  const formItemLayout = {
    labelCol: {
      xs: { span: 24 },
      sm: { span: 8 },
    },
    wrapperCol: {
      xs: { span: 24 },
      sm: { span: 16 },
    },
  };

  return (
    <div className={style.container}>
      <div className={style.card}>
        <div className={style.cardContent}>
          <div className={style.firstLine}>
            <div className={style.left}>
              <div className={style.firstLineLabel}>员工姓名：</div>
              <Input className={style.input} onChange={(e) => { setCondition({ name: e.target.value }) }} placeholder="请输入员工姓名" />
              <Button className={style.search} onClick={queryClickHandler}>查询</Button>
            </div>
            <Button className={style.addEmployees} onClick={clickHandler}>+添加员工</Button>
          </div>
          <div className={style.tableContainer}>
            <Table
              columns={columns}
              dataSource={employeeList}
              pagination={{
                current: pageObject.currentPage,
                pageSize: pageObject.pageNum,
                total: pageObject.total,
              }}
              onChange={handleTableChange}
            />
          </div>
          <Modal open={visible} footer={null} onCancel={cancelOnClick}>
            <Card className={style.modalCard} title="添加员工">
              <Form {...formItemLayout} form={form}
                className={style.form}>
                <Form.Item
                  name="account"
                  label="账号"
                  rules={[
                    { required: true, message: '请输入账号!' },
                    { pattern: /^[a-zA-Z0-9]{6,20}$/, message: '账号只能是6-20位字母或数字' }
                  ]}
                >
                  <Input />
                </Form.Item>
                <Form.Item
                  name="name"
                  label="员工姓名"
                  rules={[
                    { required: true, message: '请输入员工姓名' },
                    { pattern: /^[\u4e00-\u9fa5]{2,8}$/, message: '员工姓名只能是2-4位汉字' }
                  ]}
                >
                  <Input />
                </Form.Item>
                <Form.Item
                  name="phoneNumber"
                  label="手机号"
                  rules={[
                    { required: true, message: '手机号' },
                    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' }
                  ]}
                >
                  <Input />
                </Form.Item>

                <Form.Item
                  name="gender"
                  label="性别"
                >
                  <Radio.Group  >
                    <Radio value={1}>男</Radio>
                    <Radio value={2}>女</Radio>
                  </Radio.Group>
                </Form.Item>

                <Form.Item
                  name="identificationNumber"
                  label="身份证号"
                  rules={[
                    { pattern: /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}(\d|X|x)$/, message: '请输入有效的身份证号' }
                  ]}
                >
                  <Input />
                </Form.Item>
              </Form>
            </Card>
            <Row gutter={5} type="flex" align="middle" justify="center">
              <Col><Button onClick={saveOnClick}>保存</Button></Col>
              <Col><Button onClick={saveAndKeepAddingOnClick}>保存并继续添加员工</Button></Col>
              <Col><Button onClick={cancelOnClick}>退出</Button></Col>
            </Row>
          </Modal>
        </div>
      </div>
    </div>
  );
}